import * as React from 'react'

type Theme = 'light' | 'dark' | 'system'

type ThemeContextValue = {
    theme: Theme
    setTheme: (theme: Theme) => void
}

const ThemeContext = React.createContext<ThemeContextValue | undefined>(undefined)

function getSystemPrefersDark(): boolean {
    return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
}

function applyTheme(theme: Theme) {
    const root = document.documentElement
    const isDark = theme === 'dark' || (theme === 'system' && getSystemPrefersDark())
    root.classList.toggle('dark', isDark)
}

export function ThemeProvider({ children, defaultTheme = 'system' as Theme }: { children: React.ReactNode; defaultTheme?: Theme }) {
    const [theme, setThemeState] = React.useState<Theme>(() => {
        const stored = localStorage.getItem('theme') as Theme | null
        return stored ?? defaultTheme
    })

    React.useEffect(() => {
        applyTheme(theme)
        localStorage.setItem('theme', theme)
    }, [theme])

    React.useEffect(() => {
        const media = window.matchMedia('(prefers-color-scheme: dark)')
        const handler = () => {
            if (localStorage.getItem('theme') === 'system') {
                applyTheme('system')
            }
        }
        media.addEventListener('change', handler)
        return () => media.removeEventListener('change', handler)
    }, [])

    const setTheme = React.useCallback((t: Theme) => setThemeState(t), [])

    return (
        <ThemeContext.Provider value={{ theme, setTheme }}>{children}</ThemeContext.Provider>
    )
}

export function useTheme() {
    const ctx = React.useContext(ThemeContext)
    if (!ctx) throw new Error('useTheme must be used within ThemeProvider')
    return ctx
}


